package com.xone.xapp;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.xone.refresh.library.PullToRefreshBase;
import com.xone.refresh.library.PullToRefreshBase.Mode;
import com.xone.refresh.library.PullToRefreshBase.OnRefreshListener;
import com.xone.refresh.library.PullToRefreshListView;

public abstract class BasicListActivity<T extends BasicListHolder> extends BasicActivity {
	
	protected final String TAG = BasicListActivity.class.getSimpleName();

	/**
	 * 取得当前的列表视图
	 * @return
	 */
	public abstract PullToRefreshListView getListView();
	
	/**
	 * 取得当前的列表适配器
	 * @return
	 */
	public abstract BasicListAdapter<T> getListAdapter(Context context, List<JSONObject> result);
	
	/**
	 * 取得当前请求的地址
	 * @return
	 */
	public abstract String getRequestURL();
	
	/**
	 * 请求的参数集合
	 * @return
	 */
	public abstract List<NameValuePair> getRequestParams();
	
	/**
	 * 返回的JSON对象列表根名称
	 * @return
	 */
	public abstract String getJsonRootName();
	
	/**
	 * 请求数据
	 * @param params
	 * @return
	 */
	protected List<JSONObject> httpRequest(List<NameValuePair> params) {
		return HttpUtils.httpGet(Constants.APP_URL + getRequestURL(), params, new HttpUtils.onGetSuccessListener<List<JSONObject>>() {
			@Override
			public List<JSONObject> onSuccess(int status, String result) {
				if (HttpUtils.SC_OK == status) {
					return JSONUtils.getJSONListFromIdentifyString(result, getJsonRootName());
				} else {
					Log.i("HttpUtils", "Status Code:" + status);
				}
				return null;
			}
		}, getContext());
	}
	
	/**
	 * 向下拉动（刷新上部分）时的参数配置
	 * @param params
	 * @return
	 */
	public List<NameValuePair> onPullDownParams(BasicListAdapter<T> adapter, List<NameValuePair> params) {
		if (null == params) {
			params = new ArrayList<NameValuePair>();
		}
		params.add(new BasicNameValuePair("itemaction", "down"));
		int count = adapter.getCount();
		int topIndex = adapter.getTopLastIndex();
		// Do work to refresh the list here.
		if (count > 0 ) {//&& (topIndex + 1 != count)
			T first = null;
			System.out.println("onPullDownParams count:" + count + ", topIndex:" + topIndex);
			try {
				first = adapter.getItem(topIndex + 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (null != first && StringUtils.isNotBlank(first.getDateCreated())) {
				System.out.println("first is not null and first date created is not blank.");
				params.add(new BasicNameValuePair(first.getDataCreatedName(), first.getDateCreated()));
			}
			return params;
		}
		return params;
	}
	/**
	 * 向上拉动（刷新下部分）时的参数配置
	 * @param adapter
	 * @param params
	 * @return
	 */
	public List<NameValuePair> onPullUpParams(BasicListAdapter<T> adapter, List<NameValuePair> params) {
		if (null == params) {
			params = new ArrayList<NameValuePair>();
		}
		params.add(new BasicNameValuePair("itemaction", "up"));
		int count = adapter.getCount();
		System.out.println("onPullUpParams adapter count:" + count);
		if (count > 0) {
			T last = adapter.getItem(count - 1);
			if (StringUtils.isNotBlank(last.getDateCreated())) {
				System.out.println("onPullUpParams last date created:" + last.getDateCreated());
				params.add(new BasicNameValuePair(last.getDataCreatedName(), last.getDateCreated()));
			}
			return params;
		}
		return params;
	}
	
	public class InitDataTask extends AsyncTask<List<NameValuePair>, Boolean, List<JSONObject>> {
		protected Context context;
		protected PullToRefreshListView listView;
		protected BasicListAdapter<T> adapter;
		public InitDataTask(Context context, PullToRefreshListView listView) {
			this.context = context;
			this.listView = listView;
			this.listView.setMode(Mode.BOTH);//上下均可滑动
			this.listView.setScrollingWhileRefreshingEnabled(false);//刷新中禁止滚动
		}

		@Override
		protected List<JSONObject> doInBackground(List<NameValuePair>... params) {
			if (isCancelled()) {
				return null;
			}
			if (null == params || params.length == 0) {
				return httpRequest(null);
			}
			return httpRequest(params[0]);
		}
		
		@Override
		protected void onPostExecute(List<JSONObject> result) {
			super.onPostExecute(result);
			hideProgress();
			if (null == result || result.isEmpty()) {
				return;
			}
			if (null == adapter) {
				adapter = getListAdapter(context, result);//;new ProductAdapter(context, result);
				listView.getRefreshableView().setAdapter(adapter);
			}
			//监听列表被刷新时事件.
			listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@SuppressWarnings("unchecked")
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					int flags=DateUtils.FORMAT_SHOW_TIME
							| DateUtils.FORMAT_SHOW_DATE
							| DateUtils.FORMAT_ABBREV_ALL;
					String label = DateUtils.formatDateTime(getApplicationContext(),System.currentTimeMillis(),flags);
					// 更新最后刷新时间
					refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
					List<NameValuePair> req = getRequestParams();
					PullLoadDataTask task = new PullLoadDataTask(listView, adapter);
					if (Mode.PULL_FROM_START.compareTo(listView.getCurrentMode()) == 0) {//向下拉动增加数据, 下拉新增数据
						task.execute(onPullDownParams(adapter, req));
					} else {//上拉新增数据
						task.execute(onPullUpParams(adapter, req));
					}
				}
			});
//			// Set a listener to be invoked when the list should be refreshed.
//			listView.setOnRefreshListener(new OnRefreshListener() {
//				@SuppressWarnings("unchecked")
//				public void onRefresh() {
//					int count = adapter.getCount();
//					int topIndex = adapter.getTopLastIndex();
//					PullToRefreshDataTask task = new PullToRefreshDataTask(listView, adapter);
//					// Do work to refresh the list here.
//					if (count > 0 && (topIndex + 1 != count)) {
//						T first = adapter.getItem(topIndex + 1);
//						List<NameValuePair> params = getRequestParams();
//						if (null == params) {
//							params = new ArrayList<NameValuePair>();
//						}
//						params.add(new BasicNameValuePair("itemaction", "down"));
//						if (StringUtils.isNotBlank(first.getDateCreated())) {
//							params.add(new BasicNameValuePair(first.getDataCreatedName(), first.getDateCreated()));
//						}
//						task.execute(params);
//					} else {
//						task.execute(getRequestParams());
//					}
//				}
//			});
			// set a listener to be invoked when the list reaches the end
//			listView.setOnLoadMoreListener(new OnLoadMoreListener() {
//				@SuppressWarnings("unchecked")
//				public void onLoadMore() {
//					// Do the work to load more items at the end of list here
//					int count = adapter.getCount();
//					LoadMoreDataTask task = new LoadMoreDataTask(listView, adapter);
//					if (count > 0) {
//						T last = adapter.getItem(count - 1);
//						List<NameValuePair> params = getRequestParams();
//						if (null == params) {
//							params = new ArrayList<NameValuePair>();
//						}
//						params.add(new BasicNameValuePair("itemaction", "up"));
//						if (StringUtils.isNotBlank(last.getDateCreated())) {
//							params.add(new BasicNameValuePair(last.getDataCreatedName(), last.getDateCreated()));
//						}
//						task.execute(params);
//					} else {
//						task.execute(getRequestParams());
//					}
//				}
//			});
		}
	}
	
	public class PullLoadDataTask extends AsyncTask<List<NameValuePair>, Void, List<JSONObject>> {
		protected PullToRefreshListView listView;
		protected BasicListAdapter<T> adapter;
		public PullLoadDataTask(PullToRefreshListView listView, BasicListAdapter<T> adapter) {
			this.listView = listView;
			this.adapter = adapter;
		}
		@Override
		protected List<JSONObject> doInBackground(List<NameValuePair>... params) {
			if (isCancelled()) {
				return null;
			}
			return httpRequest(params[0]);
		}
		@Override
		protected void onPostExecute(List<JSONObject> result) {
			if (null != result && result.size() > 0) {
				List<T> list = adapter.initWithJsonList(result);
				if (null != list && !list.isEmpty()) {
					if (Mode.PULL_FROM_START.compareTo(listView.getCurrentMode()) == 0) {//向下拉动增加数据, 下拉新增数据
						int topIndex = adapter.getTopLastIndex();
						adapter.getList().addAll((topIndex + 1), list);
					} else {//上拉新增数据
						adapter.getList().addAll(list);
					}
					// We need notify the adapter that the data have been changed
					((BaseAdapter) adapter).notifyDataSetChanged();
				}
			}
			//当数据加载完成，需要调用onRefreshComplete.
			listView.onRefreshComplete();
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			// Notify the loading more operation has finished
			listView.onRefreshComplete();
		}
		
	}
	
//	public class LoadMoreDataTask extends AsyncTask<List<NameValuePair>, Void, List<JSONObject>> {
//		protected PullAndLoadListView listView;
//		protected BasicListAdapter<T> adapter;
//		public LoadMoreDataTask(PullAndLoadListView listView, BasicListAdapter<T> adapter) {
//			this.listView = listView;
//			this.adapter = adapter;
//		}
//		@Override
//		protected List<JSONObject> doInBackground(List<NameValuePair>... params) {
//			if (isCancelled()) {
//				return null;
//			}
//			return httpRequest(params[0]);
//		}
//		@Override
//		protected void onPostExecute(List<JSONObject> result) {
//			if (null != result && result.size() > 0) {
//				adapter.getList().addAll(adapter.initWithJsonList(result));
//				// We need notify the adapter that the data have been changed
//				((BaseAdapter) adapter).notifyDataSetChanged();
//			}
//			// Call onLoadMoreComplete when the LoadMore task, has finished
//			listView.onLoadMoreComplete();
//			super.onPostExecute(result);
//		}
//		@Override
//		protected void onCancelled() {
//			// Notify the loading more operation has finished
//			listView.onLoadMoreComplete();
//		}
//	}
//
//	public class PullToRefreshDataTask extends AsyncTask<List<NameValuePair>, Void, List<JSONObject>> {
//		protected PullAndLoadListView listView;
//		protected BasicListAdapter<T> adapter;
//		public PullToRefreshDataTask(PullAndLoadListView listView, BasicListAdapter<T> adapter) {
//			this.listView = listView;
//			this.adapter = adapter;
//		}
//		@Override
//		protected List<JSONObject> doInBackground(List<NameValuePair>... params) {
//			if (isCancelled()) {
//				return null;
//			}
//			return httpRequest(params[0]);
//		}
//		@Override
//		protected void onPostExecute(List<JSONObject> result) {
//			if (null != result && result.size() > 0) {
//				int topIndex = adapter.getTopLastIndex();
//				adapter.getList().addAll((topIndex + 1), adapter.initWithJsonList(result));
//				// We need notify the adapter that the data have been changed
//				((BaseAdapter) adapter).notifyDataSetChanged();
//			}
//			// Call onRefreshComplete when the LoadMore task, has finished
//			listView.onRefreshComplete();
//			super.onPostExecute(result);
//		}
//		@Override
//		protected void onCancelled() {
//			// Notify the loading more operation has finished
//			listView.onRefreshComplete();
//		}
//	}
	
}
